/*
 *  Server Utility functions source file.
 *  Ower - 
*/
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include <string.h>
#include<signal.h>
#include<sys/wait.h>

#include "util.h"
#include "server_utils.h"

void shutdown_server (int error, char *errmsg)
{
    if (error == SRVRE_GRACEFUL_SHUTDOWN){
        LOG(CRITICAL, "Shutting down gracefully...");
        //ToDO (Atul) : wait till all the threads join.
    }else{
        LOG(CRITICAL, "%d Abnormal server shutdown", error);
    }
    
    LOG(CRITICAL, "%d %s", error, errmsg);    
    exit(error);
}

void request_graceful_shutdown ()
{
    LOG(WARN, "Graceful shutdown requested...");
    g.graceful_shutdown_request = TRUE;
    return;
}



/* ToDo: (atul) handle signals
   Timeout - SIGALRM
   Interrupt - SIGINTR
   SIGKILL and SIGSTOP can not be handled.
   SIGIO, SIGPOLL, SIGURG - need special handling.
   SIG_IGN --to suppress signal.
   SIG_DEF --to set default handler.
*/
sigfunc *
set_signal_handler(int signo, sigfunc *func)
{
    struct sigaction act, oact;

    act.sa_handler = func;
    sigemptyset(&act.sa_mask);//no other signal is masked.
    act.sa_flags = 0;
    
    if (signo == SIGALRM) {
#ifdef SA_INTERRUPT
        act.sa_flags |= SA_INTERRUPT; /* SunOS 4.x*/
#endif/* Externally defined functions -- should be moved to resepctive .h */

    }else{
        /* Restart system calls if interrupted */
#ifdef SA_RESTART
        act.sa_flags |= SA_RESTART; /* SVR4, 4.4BSD */
#endif
    }

    if (sigaction(signo, &act, &oact) < 0 )
        return (SIG_ERR);

    return (oact.sa_handler);
}

void
sig_chld(int signo)
{

    pid_t pid;
    int stat;

    while((pid == waitpid(-1, &stat, WNOHANG)) > 0)
        LOG(INFO, "child %d terminated\n", pid);

    return;
}

void
sig_alrm(int signo)
{
    LOG(DEBUG, "Inside alram signal handler");
    
}

void
sig_int(int signo)
{
    LOG(DEBUG, "Inside interupt signal handler");
    shutdown_server(SRVRE_INTERRUPT, "Abrupt stop by interrupt, SIGINT");
}

void
sig_pipe(int signo)
{
    LOG(DEBUG, "Inside pipe signal handler");
    
}
